package com.party.api.service.idcard.impl;

import cn.jpush.api.utils.Nullable;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.party.api.dto.idcard.request.IdcardVerifyRequest;
import com.party.api.dto.idcard.response.IdcardVerifyResponse;
import com.party.api.dto.idcard.response.IdcardVerifyResult;
import com.party.api.service.idcard.IIdcardVerifyService;
import com.party.common.utils.StringUtils;
import com.show.api.ShowApiRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by admin on 2018/4/10.
 */

@Service
public class IdcardVerifyService implements IIdcardVerifyService {

    protected static Logger logger = LoggerFactory.getLogger(IdcardVerifyService.class);

    /**
     * 身份证姓名验证
     *
     * @param request 请求参数
     * @return 验证结构
     * @throws Exception 异常信息
     */
    @Override
    public IdcardVerifyResult verify(IdcardVerifyRequest request) throws Exception {
        String idcard = request.getIdcard();
        String name = request.getName();
        if (StringUtils.isNotEmpty(idcard)) {
            idcard = idcard.trim().replaceAll(" ", "");
        }
        if (StringUtils.isNotEmpty(name)) {
            name = name.trim().replaceAll(" ", "");
        }
        // 前置参数验证
        checkNotNull(request, "请求参数不能为空");
        checkNotNull(request.getAppid(), "appid 不能为空");
        checkNotNull(request.getAppSecret(), "appSecret 不能为空");
        checkNotNull(idcard, "idcard 不能为空");
        checkNotNull(name, "name 不能为空");

        //调用服务商接口
        IdcardVerifyResponse idcardVerifyResponse = null;
        Map<String, Object> requestMap = Maps.newHashMap();
        requestMap.put("appid", request.getAppid());
        requestMap.put("secret", request.getAppSecret());
        requestMap.put("idcard", idcard);
        requestMap.put("name", name);
        try {
            //"61517", "b94b80c3a54041619943113997c5d189"
            logger.info("身份证验证请求报文{}", JSONObject.toJSONString(request));
            String response = new ShowApiRequest("http://route.showapi.com/1072-1",
                    request.getAppid(), request.getAppSecret())
                    .addTextPara("idcard", idcard)
                    .addTextPara("name", name)
                    .post();

            logger.info("身份证验证响应报文{}", response);
            JSONObject jsonObject = JSONObject.parseObject(response);
            idcardVerifyResponse = JSONObject.toJavaObject(jsonObject, IdcardVerifyResponse.class);
            Map<String, Object> resBodyMap = null != jsonObject.get("showapi_res_body") ? JSONObject.parseObject(jsonObject.get("showapi_res_body").toString(), Map.class) : null;
            if (null != resBodyMap) {
                String data = null != resBodyMap.get("data") ? resBodyMap.get("data").toString() : null;
                if (StringUtils.isNotEmpty(data)) {
                    IdcardVerifyResult tempResult = JSONObject.parseObject(data, IdcardVerifyResult.class);
                    idcardVerifyResponse.setResult(tempResult);
                }
            }
            if (!idcardVerifyResponse.getResCode().equals("0")) {
                logger.error("身份证验证返回报文异常:{}；请求报文:{}", response, JSONObject.toJSONString(requestMap));
                throw new Exception(response);
            }
            return idcardVerifyResponse.getResult();
        } catch (Exception e) {
            logger.error("身份证验证请求异常：请求报文：{}", e, JSONObject.toJSONString(requestMap));
            throw e;
        }
    }

    public static void main(String[] args) throws Exception {
        IdcardVerifyService idcardVerifyService = new IdcardVerifyService();
        IdcardVerifyRequest request = new IdcardVerifyRequest();
        request.setAppid("61517");
        request.setAppSecret("b94b80c3a54041619943113997c5d189");
        request.setIdcard("");
        request.setName("");
        IdcardVerifyResult result = idcardVerifyService.verify(request);
        if (new Integer(0).equals(result.getCode())) {
            System.out.println("验证成功");
        } else if (new Integer(1).equals(result.getCode())) {
            System.out.println("身份证与姓名不匹配");
        } else if (new Integer(101).equals(result.getCode())) {
            System.out.println("验证信息重复输入，避免恶意验证请间隔30秒以上再次核验");
        }
    }

    public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
        if (reference == null) {
            throw new NullPointerException(String.valueOf(errorMessage));
        }
        if (reference instanceof String) {
            if (StringUtils.isEmpty((CharSequence) reference)) {
                throw new NullPointerException(String.valueOf(errorMessage));
            }
        }
        return reference;
    }
}
